#include "janna/plugins/coreplugin/coreplugin.h"

#include <QGuiApplication>
#include <QScreen>

#include "janna/libs/utils/log_util.h"
#include "janna/plugins/coreplugin/core.h"

namespace janna {

CorePlugin::CorePlugin() {
    this->log = LogUtil::getLogger("plugin-CorePlugin");
}

QString CorePlugin::pluginName() {
    return "CorePlugin";
}
QString CorePlugin::pluginVersion() {
    return AppConfig::getInstance()->appVersion();
}
QString CorePlugin::author() {
    return "janna";
}

QMap<QString, QVariant> CorePlugin::handler(const JannaTopic& topic, const QMap<QString, QVariant>& param) {
    if ("janna" == topic.source && "echo-core" == topic.topic) {
        SPDLOG_LOGGER_DEBUG(this->log, fmt::format("plugin-coreplugin ===> message is : {}", param.value("msg").toString().toStdString()));
        return {};
    }
    return {};
}

/**
 * 是否在主屏幕显示
 */
#define SHOW_WINDOW_IN_PRIMARY_SCREEN 1
/**
 * @brief 窗口居中
 * @param w 主窗口实例
 */
static void setWindowInCenter(QMainWindow* win) {
#if SHOW_WINDOW_IN_PRIMARY_SCREEN
    // 获取主屏幕的指针
    QScreen* primaryScreen = QGuiApplication::primaryScreen();
    // 获取主屏幕的可用工作区几何信息
    QRect availableGeometry = primaryScreen->availableGeometry();
#else
    // 获取当前屏幕的可用工作区几何信息
    QScreen* currentScreen     = QGuiApplication::screenAt(win->pos());
    QRect    availableGeometry = currentScreen->availableGeometry();
#endif
    // 计算窗口居中显示的位置
    int x = availableGeometry.x() + (availableGeometry.width() - win->width()) / 2;
    int y = availableGeometry.y() + (availableGeometry.height() - win->height()) / 2;

    // 移动窗口到居中的位置
    win->move(x, y);
}

bool CorePlugin::initialize(QString* error_message) {
    Q_UNUSED(error_message)

    auto coreIns = janna_core_core_getInstance();

    coreIns->initMainWindow();
    auto win = coreIns->mainwindow();
    setWindowInCenter(win);
    win->show();

    return true;
}

};  // namespace janna